import React, { useState } from 'react'
import "./Choice.less"
import ChoiceItem from '../ChoiceItem/ChoiceItem'
interface Iprops {
  data: IQuesData
}
interface IQueType {
  [k: string]: string
}

export default function Choice(props: Iprops) {
  let { data } = props
  let [ischeck, setCheck] = useState<string[]>([])//存储当前用户选择的选项，使用数组单选多选都能存里面
  let [msg, setMsg] = useState("")
  // console.log(data.optionContent)
  let options: Ioption[] = JSON.parse(data.optionContent)
  let QueType: IQueType = {
    many: "多选",
    one: "单选",
    check: "判断"
  }

  const xuan = (v: string) => {
    //控制选项的方法
    // console.log("儿子给的", v);
    //把v放到ischeck数组中,单选走替换，多选是追加
    if (data.questionType !== "many") {
      //单选，替换
      let newarr = [v]
      setCheck(newarr)
    } else {
      //多选，追加
      let newarr = JSON.parse(JSON.stringify(ischeck))
      //判断当前单击的选项是否在数组中，不在就添加，在就不添加
      if (newarr.includes(v)) {
        //在 截取
        let begin = newarr.indexOf(v)
        newarr.splice(begin)
        setCheck(newarr)
      } else {
        //不在 添加
        newarr.push(v)
        setCheck(newarr)
      }
      // console.log(newarr);
    }
  }

  const tijiao = () => {
    //提交，验证答案answer
    //先对用户的选择进行一个排序
    let userAnswer = ischeck.sort().join(",")
    console.log(userAnswer);
    if (userAnswer === data.answer) {
      setMsg("回答正确");
    } else {
      setMsg("回答错误");
    }
  }

  return (
    <div className='choice'>
      <div className="top">
        <div className='type'>{QueType[data.questionType]}</div>
        <div className='question'>{data.title}</div>
      </div>
      <div className="option">
        {
          options.map((item, index) => {
            return (
              <ChoiceItem
                key={index}
                data={item}
                ischeck={ischeck.includes(item.key)}
                xuan={xuan}
              ></ChoiceItem>
            )
          })
        }
      </div>
      <button onClick={tijiao}>提交</button>
      {msg}
    </div>
  )
}
